﻿using PLC.Interface.Authorizes;
using PLC.Interface.BaseUsers;
using PLC.Interface.Devices;
using PLC.Interface.Groups;
using PLC.Interface.Stations;
using PLCWpfTest.Common;
using System.Threading.Tasks;
using YWM;
using YWM.Common.Exceptions;
using YWM.Session;

namespace PLCWpfTest.ViewModels
{
    public class LoginViewModel : BaseViewModel
    {
        private readonly IAuthorizeAppService _authorizeAppService;

        public RelayCommand LanguageSelectCommand { get; set; }

        public AsyncRelayCommand LoginCommand { get; private set; }

        public LoginDto Login { get; set; } = new LoginDto();

        public LoginViewModel(IAuthorizeAppService authorizeAppService, AsyncRelayCommand loginCommand, RelayCommand languageSelectCommand)
        {
            SetLang();
            _authorizeAppService = authorizeAppService;

            LoginCommand = loginCommand;
            LoginCommand.BeforeCanExecute += LoginCommand_BeforeCanExecute;
            LoginCommand.Executing += LoginCommand_Executing;
            LoginCommand.UnexecutedFriendlyException += LoginCommand_UnexecutedFriendlyException;

            LanguageSelectCommand = languageSelectCommand;
            LanguageSelectCommand.Executing += LanguageSelectCommand_Executing; 
        }

        protected override async Task LoadCommand_Executing(object parameter)
        {
            IStationAppService stationAppService = YApp.Resolve<IStationAppService>();
            IDeviceAppService deviceAppService = YApp.Resolve<IDeviceAppService>();
            IGroupAppService groupAppService = YApp.Resolve<IGroupAppService>();
            DataCache.Stations = await stationAppService.GetTopList();
            CommunicationCache.Device = await deviceAppService.Get();
            CommunicationCache.Groups = await groupAppService.GetList(true);
        }

        private bool LoginCommand_BeforeCanExecute(object parameter)
        {
            return CommunicationCache.Groups?.Count > 0 && Login.IsValidated;
        }

        private async Task LoginCommand_Executing(object parameter)
        {
            Login.Error = string.Empty;
            BaseUserResultDto baseUser = await _authorizeAppService.Login(Login);
            DataCache.LoginUserInfo = baseUser;
            ISession session = YApp.Resolve<ISession>();
            session.SubjectId = DataCache.LoginUserInfo.Id;
            RaiseRequestClose();
        }

        private void LoginCommand_UnexecutedFriendlyException(FriendlyException ex)
        {
            Login.Error = ex.Message;
        }

        public virtual void LanguageSelectCommand_Executing(object parameter)
        {
            SetLang();
        }
    }
}